package com.surveillance.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import javax.servlet.http.HttpSession;

import com.surveillance.BO.UserBO;
import com.surveillance.entities.User;
import com.surveillance.util.LoadBeans;
import com.surveillance.validators.AuthValidator;

@Controller
@SessionAttributes("userSession")
public class AuthController {
	private AuthValidator authValidator;

	@Autowired
	public AuthController(AuthValidator authValidator) {
		super();
		this.authValidator = authValidator;
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	String renderDefaultView(ModelMap model, HttpSession session) {
		if(session.getAttribute("userSession")!=null){
			return "redirect:/welcomePage";
		}else{
			User user = new User();
			model.addAttribute("user", user);
			return "autentification";
		}
		
	}

	@RequestMapping(value = "/", method = RequestMethod.POST)
	String renderTriggerAuth(@ModelAttribute("user") User user,
			BindingResult result, SessionStatus status, ModelMap map,
			HttpSession session) {

		authValidator.validate(user, result);
		if (result.hasErrors()) {
			map.addAttribute("pageTitle", new String("page d'authentification"));
			return "autentification";
		} else {
			UserBO userBO =(UserBO) LoadBeans.getUserBO();
			User fetchedUser = (User) userBO.authenticate(user.getLogin(), user.getPassword());
			session.setAttribute("userSession", fetchedUser);
			return "redirect:/welcomePage";
		}
	}
	@RequestMapping(value = "/logOut", method = RequestMethod.GET)
	public String logOut(HttpSession session){
		session.invalidate();
		return "redirect:/";
		
	}

}
